﻿using ManageSystem.Model;
using ManageSystem.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace ManageSystem.Controllers
{
    /// <summary>
    /// ADD and manage project
    /// </summary>
    [Route("ManageSystem/[controller]/[action]")]
    [ApiController]
    [Produces("application/json")]
    public class ProjectController : ControllerBase
    {
        // service
        public ProjectService projectService = new();

        public IncomeStreamService incomeStreamService = new(
          );
        public OutlayStreamService outlayStreamService = new();

        // 注入IWebHostEnvironment
        private readonly IWebHostEnvironment _webHostEnvironment;

        public ProjectController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

        ///<summary>
        ///添加项目。登陆以后的任意角色(level1)都可以。级联插入只能同步
        ///</summary>
        ///<param name="project"></param>
        ///<returns></returns>
        [HttpPost]
        [Authorize(Policy = "Permission")]
        public async Task<IActionResult> AddProject(Project project)
        {
            bool isSuccess = await projectService.Add(project);
            if (isSuccess)
            {
                return Ok($"添加项目成功");
            }
            else
            {
                return NotFound($"已存在名称重复的项目，请重新命名");
            }
        }
        /// 批量添加项目
        [HttpPost]
        [Authorize(Roles = "admin")]
        public IActionResult AddPrjectList(List<Project> projects)
        {
            int successUpload = 0, failedUpload = 0;

            projects.ForEach(async project =>
            {
                bool isRepated = await projectService.isProjectNameRepated(project.projectName);
                if (isRepated)
                {
                    failedUpload += 1;
                }
                else
                {
                    await projectService.Add(project);
                    successUpload += 1;
                }
            });
            return Ok($"导入项目成功。共{projects.Count}条，成功{successUpload}条，失败{failedUpload}条");
        }

        ///<summary>
        ///删除项目
        ///</summary>
        ///<param name="projectGuid"></param>
        ///<returns></returns>
        [HttpDelete]
        [Authorize(Policy = "Permission")]
        public async Task<IActionResult> DeleteProject(string projectGuid)
        {

            // 删除项目资源
            string rootFilePath = Path.Combine(_webHostEnvironment.ContentRootPath, "uploads");
            string projectFilePath = Path.Combine(rootFilePath, projectGuid);

            // 有些项目如导入的可能没有该目录
            if (Directory.Exists(projectFilePath))
            {
                // 当前项目文件目录对象
                DirectoryInfo dir = new DirectoryInfo(projectFilePath);
                //返回目录中所有文件和子目录
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();
                foreach (FileSystemInfo i in fileinfo)
                {
                    //判断是否文件夹
                    if (i is DirectoryInfo)
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        //删除子目录和文件
                        subdir.Delete(true);
                    }
                    else
                    {
                        //删除指定文件
                        System.IO.File.Delete(i.FullName);
                    }
                }

                System.IO.Directory.Delete(projectFilePath);
            }

            // 删除项目
            bool isSuccess = await projectService.DeleteByPrimaryKey(projectGuid);
            // 删除收入流水
            int deletedIncomeStreamsNum = await incomeStreamService.DeleteIncomeStreamByProjectGuid(projectGuid);
            // 删除支出流水
            int deletedOutlayStreamsNum = await outlayStreamService.DeleteOutlayStreamByProjectGuid(projectGuid);

            if (isSuccess)
            {
                // return Ok($"删除项目成功, 关联该项目的{deletedIncomeStreamsNum}条收入流水,{deletedOutlayStreamsNum}条支出流水及附件已删除");
                return NoContent();
            }
            else
            {
                return BadRequest("删除项目失败！");
            }
        }

        ///<summary>
        ///更新项目
        ///</summary>
        ///<param name="project"></param>
        ///<returns></returns>
        [HttpPut]
        [Authorize(Policy = "Permission")]
        public async Task<IActionResult> UpdateProject(Project project)
        {
            // incomestreams of project
            List<IncomeStream> incomeStreams = await incomeStreamService.QueryIncomeStreamByProjectGuid(project.projectGuid);
            // outlaystream
            List<OutlayStream> outlayStreams = await outlayStreamService.QueryOutlayStreamByProjectGuid(project.projectGuid);
            // in this function , project will be updated
            List<IncomeStream> updatedIncomeStreams = await projectService.DealWithChangedAmountOfProject(project, incomeStreams);

            try
            {
                // 更新流水
                updatedIncomeStreams.ForEach(async incomeStream =>
                {
                    await incomeStreamService.Update(incomeStream);
                });
                outlayStreams.ForEach(async outlayStream =>
                {
                    outlayStream.projectName = project.projectName;
                    await outlayStreamService.Update(outlayStream);
                });
                return Ok($"更新项目成功,对应的收入和支出流水信息已同步更新");
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }

        }


        /// <summary>
        /// 根据username查询项目(多对多条件查询，异步)
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public async Task<IActionResult> QueryProjectsByUserName(string username)
        {
            List<Project> projects = await projectService.QueryProjectsByUserName(username);
            // return
            if (projects.Count > 0)
            {
                return Ok(projects);
            }
            else
            {
                return NotFound($"查询不到与用户[{username}]相关联的项目！");
            }
        }

        /// <summary>
        /// 查询所有项目
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public async Task<IActionResult> QueryAllProject()
        {
            List<Project> projects = await projectService.QueryAll();

            if (projects.Count > 0)
            {
                return Ok(projects);
            }
            else
            {
                return NotFound("当前数据库无项目,请先录入");
            }
        }

        /// <summary>
        /// 查询某个项目
        /// </summary>
        /// <param name="projectGuid"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Policy = "Permission")]
        public async Task<IActionResult> QueryProjectByProjectGuid(string projectGuid)
        {
            Project project = await projectService.QueryByPrimaryKey(projectGuid);
            if (project != null)
            {
                return Ok(project);
            }
            else
            {
                return NotFound("查询项目失败！");
            }
        }
    }
}
